from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from datetime import timedelta
from database import get_db
from models import User
from schemas import UserCreate, UserLogin, UserLoginResponse, ResponseModel
from auth import (
    authenticate_user,
    create_access_token,
    get_password_hash,
    get_user_by_username,
    get_user_by_email,
    get_current_active_user
)
from config import settings

router = APIRouter(prefix="/api/auth", tags=["认证"])

@router.post("/login", response_model=ResponseModel)
async def login(user_data: UserLogin, db: Session = Depends(get_db)):
    """
    用户登录接口
    
    Args:
        user_data: 登录请求数据
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含用户信息和JWT令牌的响应
    
    Raises:
        HTTPException: 如果用户名或密码错误
    """
    # 验证用户凭据
    user = authenticate_user(db, user_data.username, user_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误",
        )
    
    # 检查用户是否被禁用
    if not user.is_active:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户账户已被禁用"
        )
    
    # 生成访问令牌
    access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    
    return ResponseModel(
        code=200,
        message="登录成功",
        data={
            "id": user.id,
            "username": user.username,
            "nickname": user.nickname,
            "email": user.email,
            "avatar": user.avatar,
            "token": access_token
        }
    )

@router.post("/register", response_model=ResponseModel)
async def register(user_data: UserCreate, db: Session = Depends(get_db)):
    """
    用户注册接口
    
    Args:
        user_data: 注册请求数据
        db: 数据库会话
    
    Returns:
        ResponseModel: 包含新用户信息的响应
    
    Raises:
        HTTPException: 如果用户名或邮箱已存在
    """
    # 检查用户名是否已存在
    if get_user_by_username(db, user_data.username):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="用户名已存在"
        )
    
    # 检查邮箱是否已存在
    if get_user_by_email(db, user_data.email):
        raise HTTPException(
            status_code=status.HTTP_409_CONFLICT,
            detail="邮箱已被注册"
        )
    
    # 创建新用户
    hashed_password = get_password_hash(user_data.password)
    db_user = User(
        username=user_data.username,
        email=user_data.email,
        hashed_password=hashed_password,
        nickname=user_data.nickname or user_data.username,
        avatar="/img/thumb.jpg"
    )
    
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    
    return ResponseModel(
        code=200,
        message="注册成功",
        data={
            "id": db_user.id,
            "username": db_user.username,
            "nickname": db_user.nickname,
            "email": db_user.email,
            "avatar": db_user.avatar
        }
    )

@router.post("/logout", response_model=ResponseModel)
async def logout(current_user: User = Depends(get_current_active_user)):
    """
    用户登出接口
    
    Args:
        current_user: 当前登录用户
    
    Returns:
        ResponseModel: 登出成功响应
    
    Note:
        在实际应用中，可以将JWT令牌加入黑名单
        这里简化处理，只返回成功响应
    """
    # TODO: 在Redis中将JWT令牌加入黑名单
    # 这里可以添加令牌黑名单逻辑
    
    return ResponseModel(
        code=200,
        message="登出成功",
        data=None
    )

@router.get("/me", response_model=ResponseModel)
async def get_current_user_info(current_user: User = Depends(get_current_active_user)):
    """
    获取当前用户信息
    
    Args:
        current_user: 当前登录用户
    
    Returns:
        ResponseModel: 包含当前用户信息的响应
    """
    return ResponseModel(
        code=200,
        message="success",
        data={
            "id": current_user.id,
            "username": current_user.username,
            "nickname": current_user.nickname,
            "email": current_user.email,
            "avatar": current_user.avatar,
            "created_at": current_user.created_at.isoformat()
        }
    )